function [ImgBinned] = binImg(img, nbin_x, nbin_y, output_size_mode)
%function [ImgBinned] = binImg(M,NBinX,NBinY,OutputSizeMode)
%Bin image into square bins with size Nbin.
%If SizeMode is omitted or = 'Same' ImgBinned is the same size as img.
%If SizeMode = 'Normal', ImgBinned is reduced by binning.

ny = size(img,1);
nx = size(img,2);

if ~exist('output_size_mode','var')
    output_size_mode = 'Same';
end

if (mod(nbin_x,1)~=0)||(mod(nbin_y,1)~=0)
    error('NBinX or NBinY was not an integer.');
end

if (nbin_x == 0)||(nbin_y==0)
    error('NBinX or NBinY was 0.');
end

if ny<nbin_y || nx<nbin_x
    error('Ny was less than NBinY, or Nx was less than NBinX')
end

if (nbin_x == 1)&&(nbin_y == 1)
    ImgBinned = img;
    return;
end

%Bin, but keep same number of pixels by duplicating.
if strcmp(output_size_mode,'Same')
    fun=@(block_struct) ...
        mean2(block_struct.data)*ones(size(block_struct.data));
    ImgBinned = zeros(size(img));
    for ii=1:size(img,3)
        ImgBinned(:,:,ii)=blockproc(img(:,:,ii),[nbin_y nbin_x],fun);
    end
    %Bin, changing number of pixels.
elseif strcmp(output_size_mode,'Normal')
    fun=@(block_struct) ...
        mean2(block_struct.data);
    %Check that can resize correctly.
    if (mod(ny,nbin_y)~=0)||(mod(nx,nbin_x)~=0)
        warning('Image size was not divisble by bin size. Rounded image size down.');
        ExtraYPts = mod(ny,nbin_y);
        ExtraXPts = mod(nx,nbin_x);
        CroppedM = img(1:end-ExtraYPts,1:end-ExtraXPts,:);
        NyCrop = size(CroppedM,1);
        NxCrop = size(CroppedM,2);
        ImgBinned = zeros(NyCrop/nbin_y,NxCrop/nbin_x,size(img,3));
        for ii=1:size(img,3)
            ImgBinned(:,:,ii) = blockproc(CroppedM(:, :, ii), [nbin_y nbin_x], fun);
        end
    else
        ImgBinned = zeros(ny/nbin_y,nx/nbin_x,size(img,3));
        for ii=1:size(img,3)
            ImgBinned(:, :, ii) = blockproc(img(:, :, ii), [nbin_y nbin_x], fun);
        end
    end
else
    error('Incorrect option given for output_size_mode in binImg.');
end


end

